//
//  DetailSheQuViewController.m
//  TravelYo
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 TravelYo. All rights reserved.
//

#import "DetailSheQuViewController.h"
#import "DetailSheQuViewCell.h"
#import "ButtonView.h"
#import "DetailZhuanTiViewController.h"
#import "GongLveViewCell.h"
#import "JieBanViewCell.h"

@interface DetailSheQuViewController ()

@property (nonatomic, retain) ButtonView *buttonView;

@property (nonatomic, assign) NSInteger num;

@end

@implementation DetailSheQuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationController.navigationBar.translucent = YES;
    // 标题
    self.navigationItem.title = self.deSQModel.name;
    self.num = 1000;
    
    self.stringArray = @[@"&forum_type=new&lat=40.02937864477287&lon=116.3373706615417&page=1&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=3D292DEC-1F82-4FE7-9AE7-A1866F5F24E7&track_os=ios%25209.0.2&v=1", @"&forum_type=digest&lat=40.02923322937662&lon=116.3374195586893&page=1&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=3D292DEC-1F82-4FE7-9AE7-A1866F5F24E7&track_os=ios%25209.0.2&v=1", @"&lat=40.02923322937662&lon=116.3374195586893&page=1&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=3D292DEC-1F82-4FE7-9AE7-A1866F5F24E7&track_os=ios%25209.0.2&v=1"];
    
    [self setUpDataWithArray:self.stringArray];
    // 注册 最新
    [self.tableView registerClass:[DetailSheQuViewCell class] forCellReuseIdentifier:@"detailSQCell"];
    // 注册 攻略
    [self.tableView registerClass:[GongLveViewCell class] forCellReuseIdentifier:@"gongLVeCell"];
    // 注册 结伴
    [self.tableView registerClass:[JieBanViewCell class] forCellReuseIdentifier:@"jieBanCell"];
    // 设置cell分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 总表头
    [self addHeaderView];
    
    // 刷新
    [self setUpRefresh];
    
}


// 加载数据
- (void)setUpDataWithArray:(NSArray *)array
{
    
    // 解析数据
    if (self.num - 1000 == 2) {
        [[TYDataManager shareManager] requestDataWithUrl:[NSString stringWithFormat:@"http://open.qyer.com/qyer/company/together_list_by_fid?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&fid=%@%@?&page=%ld", self.deSQModel.ID,array[self.num - 1000],(long)self.pageNum] block:^ (NSData *data){
            
            if (!self.isRefresh) {
                [self.jieBanArray removeAllObjects];
            }
            
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSArray *array = dataDic[@"data"];
   
            for (NSDictionary *dict in array) {
                
                JieBanModel *Jmodel = [[JieBanModel alloc] init];
                [Jmodel setValuesForKeysWithDictionary:dict];
                [self.jieBanArray addObject:Jmodel];
            }
            [self.tableView reloadData];
        }];
    }
    
    
    [[TYDataManager shareManager] requestDataWithUrl:[NSString stringWithFormat:@"http://open.qyer.com/qyer/bbs/forum_thread_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&delcache=1&forum_id=%@%@?&page=%ld", self.deSQModel.ID,array[self.num - 1000], self.pageNum] block:^(NSData *data){
        
         NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        if (self.num - 1000 == 0) {
            
            if (!self.isRefresh) {
                [self.dataArray removeAllObjects];
            }

            NSDictionary *dic = dataDic[@"data"];
            NSArray *array = dic[@"entry"];
            for (NSDictionary *dict in array) {
                SheQuDetailModel *model = [[SheQuDetailModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [self.dataArray addObject:model];
                
            }

            } else if (self.num - 1000 == 1) {
                
                if (!self.isRefresh) {
                    [self.gongLArray removeAllObjects];
                }
                
                
                NSDictionary *dic = dataDic[@"data"];
                NSArray *array = dic[@"entry"];
                for (NSDictionary *dict in array) {
                    GongLveModel *Gmodel = [[GongLveModel alloc] init];
                    [Gmodel setValuesForKeysWithDictionary:dict];
                    [self.gongLArray addObject:Gmodel];
                }
            }
        
        [self.tableView reloadData];
    }];
    
}



// 懒加载最新dataArray
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

// 懒加载 攻略
- (NSMutableArray *)gongLArray
{
    if (!_gongLArray) {
        _gongLArray = [NSMutableArray array];
    }
    return _gongLArray;
}

// 懒加载 结伴
- (NSMutableArray *)jieBanArray
{
    if (!_jieBanArray) {
        _jieBanArray = [NSMutableArray array];
    }
    return _jieBanArray;
}

- (void)setUpRefresh
{
    // 下拉刷新
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    [self.tableView.header beginRefreshing];
    
    // 上拉加载
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefreshing)];
    [self.tableView.footer beginRefreshing];
}

// 实现下拉刷新的方法
- (void)headerRereshing
{
    self.isRefresh = NO;
    [self setUpDataWithArray:self.stringArray];
    [self.tableView.header endRefreshing];
}

// 上拉加载
- (void)footerRefreshing
{
    _pageNum++;
    self.isRefresh = YES;
    self.tableView.footer.hidden = YES;
    [self setUpDataWithArray:self.stringArray];
    [self.tableView reloadData];
    [self.tableView.footer endRefreshing];
}


// 添加总表头
- (void)addHeaderView
{

    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 90)];
    self.headerView.backgroundColor = [UIColor orangeColor];
    UIImageView *headerImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 90)];
    headerImage.image = [UIImage imageNamed:@"12.png"];
    [self.headerView addSubview:headerImage];
    self.tableView.tableHeaderView = self.headerView;
    
    // 图片
    self.photoImage = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 100) / 2 - 40, 10, 90, 70)];
    self.photoImage.backgroundColor = [UIColor orangeColor];
    [self.photoImage sd_setImageWithURL:[NSURL URLWithString:self.deSQModel.photo] placeholderImage:nil];
    [self.headerView addSubview:self.photoImage];
    
    // 帖子数
    self.totalLable = [[UILabel alloc] initWithFrame:CGRectMake(self.photoImage.right + 30, self.photoImage.top + 20, 120, 30)];
   // self.totalLable.backgroundColor = [UIColor brownColor];
    self.totalLable.text = [NSString stringWithFormat:@"%@个帖子", self.deSQModel.total_threads];
    self.totalLable.alpha = 0.8;
    [self.headerView addSubview:self.totalLable];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.num == 1000) {
        return self.dataArray.count;
    } else if (self.num == 1001) {
        return self.gongLArray.count;
    } else {
        return self.jieBanArray.count;
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_num == 1000) {
      
        DetailSheQuViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"detailSQCell" forIndexPath:indexPath];
        
        
        SheQuDetailModel *model = self.dataArray[indexPath.row];
        cell.model = model;
        return cell;
        
    } else if (_num == 1001) {
    
         
    GongLveViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"gongLVeCell" forIndexPath:indexPath];
        
        GongLveModel *model = self.gongLArray[indexPath.row];
       // NSLog(@"%@", model.title);
        cell.glModel = model;
        
        return cell;
        
    } else {
        JieBanViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"jieBanCell" forIndexPath:indexPath];
        
        JieBanModel *model = self.jieBanArray[indexPath.row];
        cell.jBModel = model;
        return cell;
    
    }
        
}


// 每个分区的表头 (button在表头上)
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    self.buttonView = [[ButtonView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 70)];
    
    for (UIButton *button in self.buttonView.subviews) {
        [button addTarget:self action:@selector(actionButton:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return self.buttonView;
}

// 点击button方法  刷新界面
- (void)actionButton:(UIButton *)button
{
    // 刷新
    [self setUpRefresh];
    self.num = button.tag;
    self.dataArray = nil;
    [self setUpDataWithArray:self.stringArray];
    [self.tableView reloadData];
}


// 返回表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 70;
}

// 返回cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_num == 1000) {
        return 180;
    } else if (_num == 1001) {
    return 120;
    } else {
        return 185;
    }
    
}

// 进入详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailZhuanTiViewController *detailZTVC = [[DetailZhuanTiViewController alloc] init];
    if (self.num == 1000) {
        
        SheQuDetailModel *model = self.dataArray[indexPath.row];
        detailZTVC.url = model.view_url;
    } else if (self.num == 1001) {
        GongLveModel *model = self.gongLArray[indexPath.row];
        detailZTVC.url = model.view_url;
    } else {
        JieBanModel *model = self.jieBanArray[indexPath.row];
        detailZTVC.url = model.appview_url;
    }
    
  // 当跳转的时候隐藏tabBar
    detailZTVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailZTVC animated:YES];
}






/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
